<template>
    <w-tab-list
            @clear-search="clearSearchClick(true)"
            @refresh-data="refreshData"
            @switch-page="switchPageClick"
            @search-active="searchActive"
            @delete-batch="deleteDictClick"
            @open-add-from="addDictClick"
            @clear-selection="clearSelectionClick"
            :total="paging.total"
            :page-size="paging.pageSize"
            :frame="false"
    >
        <template #searchItem>
            <ul style="float: left">
                <li>
                    字典名称：<el-input placeholder="请输入字典名称" v-model="search.name" clearable/>
                </li>
                <li>
                    字典编码：<el-input placeholder="请输入字典编号" v-model="search.code" clearable/>
                </li>
                <li>
                    状态：<el-select placeholder="选择状态" v-model="search.enabled" style="color: lightgray" clearable>
                            <el-option label="正常" :value="1"/>
                            <el-option label="弃用" :value="0"/>
                        </el-select>
                </li>
                <li>
                    创建时间：<el-date-picker v-model="date" type="daterange" size="default" start-placeholder="开始时间" end-placeholder="结束时间" clearable class="picker"/>
                </li>
            </ul>
        </template>
        <template #batchOperationItem>
            <el-button @click="importDataClick" :icon="Upload" class="import">导入</el-button>
            <el-button @click="exportDataClick" :icon="Download" class="export">导出</el-button>
            <span style="margin: 0 20px;font-size: 13px">选择展示列</span>
            <el-checkbox v-model="display.code" label="编码" size="small"/>
            <el-checkbox v-model="display.remark" label="备注" size="small"/>
            <el-checkbox v-model="display.enabled" label="状态" size="small"/>
            <el-checkbox v-model="display.createTime" label="创建时间" size="small"/>
        </template>
        <template #dataList>
            <el-table
                    :data="tableData"
                    style="width: 100%"
                    row-key="id"
                    size="small"
                    border
                    v-loading="loading.value"
                    @select="customSelectRow"
                    @select-all="customSelectAll"
                    element-loading-text="正在加载字典表数据"
                    ref="dictTableRef"
                    :resizable="true"
            >
                <el-table-column type="selection" width="40"/>
                <el-table-column label="字典编号" prop="id" width="100"/>
                <el-table-column label="名称" prop="name"/>
                <el-table-column label="编码" prop="code" v-if="display.code"/>
                <el-table-column label="值" prop="value" width="100px"/>
                <el-table-column label="备注" v-if="display.remark">
                    <template #default="s">
                        <template v-if="s.row.remark===null || s.row.remark===''">
                            无
                        </template>
                        <template v-else>
                            {{s.row.remark}}
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="130px" v-if="display.enabled">
                    <template #default="s">
                        <el-switch v-model="s.row.enabled"
                                   :before-change="switchEnabledClick"
                                   @change="enableChange($event,s.row)"
                                   inactive-text="停用"
                                   active-text="正常"
                                   :inactive-value="0"
                                   :active-value="1"
                                   size="small"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180px" v-if="display.createTime"/>
                <el-table-column label="操作" width="220">
                    <template #default="s">
                        <el-button type="text" :icon="Edit" size="small" @click="editDictClick(s.row)">编辑</el-button>
                        <el-button type="text" :icon="Delete" size="small" @click="deleteDictClick(s.row)">删除</el-button>
                        <el-button type="text" :icon="FolderAdd" size="small" @click="addDictChildrenClick(s.row)">添加子节点</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
        <template #footer>
            <div class="explain">
                导入数据的格式：首行为表格字段，包括（字典名称、字典编码、值、备注、父编号、是否启用、创建时间、修改时间），表格数据从第二行开始。
            </div>
        </template>
    </w-tab-list>
    <dict-form width="32%" @refresh-data="refreshData" ref="dictFormRef"/>
    <dict-children width="28%" @refresh-data="refreshData" ref="dictChildrenRef"/>
    <data-import action="http://localhost:8001/sys/dict/import" @upload-success="uploadSuccess" ref="importRef"/>
    <div ref="aaa"></div>
</template>

<script>
    import {Edit,Delete,Upload,Download,Unlock,FolderAdd} from '@element-plus/icons-vue'
    import {ElLoading} from 'element-plus'
    import {deleteDict, exportDict, getDictList, updateDict} from "../../../network/sys/dict";
    import {ElMessage} from "element-plus";
    import WTabList from "../../com/WTabList.vue";
    import DictForm from "./form/DictForm.vue";
    import DictChildren from "./form/DictChildren.vue";
    import DataImport from "../../com/DataImport.vue";
    import {getCurrentInstance, reactive, ref, toRefs} from "vue";

    export default {
        name: "DictMain",
        components: {
            DictChildren,
            DataImport,
            DictForm,
            WTabList},
        setup(props,{emit}){
            const globalProperties = getCurrentInstance()?.appContext.config.globalProperties;
            const importRef = ref(null);
            const dictTableRef = ref(null);
            const dictFormRef = ref(null);
            const dictChildrenRef = ref(null);
            const searchResource = function (){
                // console.log('初始值')
                return{
                    name: null,
                    code: null,
                    enabled: null,
                    begin: null,
                    end: null
                }
            };
            const data = reactive({
                dictData: [],
                search: searchResource(),
                date: null,
                paging:{
                    pageNum: 1,
                    pageSize: 12,
                    total: 0
                },
                loading:{
                    value: false
                },
                display:{
                    code: true,
                    remark: true,
                    enabled: true,
                    createTime: true
                },
            })
            const clickEvent = reactive({
                addDictClick(){
                    let frm = dictFormRef.value;
                    frm.visible = true;//显示
                    frm.title = '添加字典';//标题
                    frm.type = 0;//表单类型
                },
                editDictClick(dict){
                    let frm = dictFormRef.value;
                    frm.visible = true;//显示
                    frm.title = '编辑字典';//标题
                    frm.type = 1;//表单类型
                    this.$nextTick(function (){
                        frm.setDict(dict);
                    })
                },
                deleteDictClick(row){
                    if(row){
                        globalProperties.$operate.remove({//确认操作
                            title: '删除字典',
                            data: `'${row.name}'`,
                            hint: '这将会删除该字典及其下的所有子字典。',
                            executeFn: ()=>{//执行操作
                                executionFn.deleteExecute([row.id]);
                            }
                        })
                    }else{
                        globalProperties.$operate.removeBatch({
                            title: '批量删除字典',
                            selection: dictTableRef.value.getSelectionRows(),
                            key: 'id',
                            executeFn: (ids)=>{
                                executionFn.deleteExecute(ids)
                            }
                        })
                    }
                },
                exportDataClick(){
                    exportDict().then(data=>{
                        globalProperties.$utils.exportExcel({
                            data: data,
                            fileName: '字典表'
                        })
                    })
                },
                importDataClick() {
                    importRef.value.visible = true;
                },
                switchEnabledClick(){
                    return globalProperties.$operate.switchStatus({
                        title: '修改字典状态',
                        hint: '你确认要更改该字典状态吗'
                    });
                },
                clearSelectionClick(){
                    dictTableRef.value.clearSelection();
                },
                switchPageClick(index){
                    data.paging.pageNum = index;
                },
                addDictChildrenClick(row){
                    let frm = dictChildrenRef.value;
                    frm.visible=true;
                    frm.title='添加子节点';
                    this.$nextTick(function (){
                        frm.setFatherDict(row);
                    })
                },
                clearSearchClick(hint){
                    globalProperties.$utils.resetSearchParams({
                        initData: searchResource(),
                        data: data.search,
                        hint: hint,
                        callback: ()=>{
                            executionFn.loadDictData();
                        }
                    });
                },
                searchActive(){
                    globalProperties.$utils.searchActive({
                        data: data.search,
                        initData: searchResource(),
                        executeFn:()=>{
                            executionFn.loadDictData();
                        }
                    })
                },
            })
            const executionFn = reactive({
                deleteExecute(ids){
                    deleteDict(ids).then(vo=>{
                        globalProperties.$response.handle({//处理执行结果
                            data: vo,
                            success: '删除成功',
                            error: '删除失败',
                            successFn: ()=>{
                                executionFn.refreshData();
                            }
                        })
                    })
                },
                enableChange($event,row){
                    // console.log('val',$event);
                    // console.log('id',row.id)
                    updateDict({id: row.id, enabled: $event}).then(vo=>{
                        globalProperties.$response.handle({
                            data: vo,
                            success: '修改成功',
                            error: '修改失败',
                            successFn: ()=>{
                                executionFn.refreshData();
                            }
                        })
                    })
                },
                refreshData(hint){
                    executionFn.loadDictData(hint);
                    clickEvent.clearSearchClick();
                },
                uploadSuccess(){
                    executionFn.refreshData();
                    importRef.value.visible=false;
                },
                loadDictData(hint){
                    data.loading.value = true;
                    data.search.begin = data.date===null?null:new Date(data.date[0]).format('yyyy-MM-dd');
                    data.search.end = data.date===null?null:new Date(data.date[1]).format('yyyy-MM-dd');
                    getDictList(data.search).then(vo=>{
                        data.loading.value = false;
                        globalProperties.$response.handle({
                            data: vo,
                            error: '获取字典数据失败',
                            successFn: ()=>{
                                data.dictData = globalProperties.$utils.convertTree({
                                    data: vo.data,
                                    id: 'id',
                                    parentId: 'parentId',
                                    children: 'children'
                                })
                                data.paging.total = data.dictData.length;
                                if(hint){
                                    ElMessage.success('刷新成功');
                                }
                            }
                        })
                    })
                },
            })
            return{
                importRef,
                dictTableRef,
                dictFormRef,
                dictChildrenRef,
                ...toRefs(data),
                ...toRefs(clickEvent),
                ...toRefs(executionFn),
                Edit, Delete, Upload, Download, Unlock, FolderAdd,
            }
        },
        data(){
            return{
                checkedAll: false
            }
        },
        created() {
            this.init();
        },
        computed: {
            tableData() {
                let no = this.paging.pageNum;
                let size = this.paging.pageSize;
                let start = (no - 1) * size;
                let end = no * size;
                return this.dictData.slice(start,end);
            }
        },
        methods: {
            customSelectRow(selection,row){
                //级联选择
                if(Array.isArray(row.children) && row.children.length!==0){
                    row.children.forEach(r=>{
                        this.$refs.dictTableRef.toggleRowSelection(r,null);
                        this.customSelectRow(null,r);
                    })
                }
            },
            customSelectAll(selection){
                this.checkedAll = !this.checkedAll;
                this.toggleCheckedAll(this.tableData,this.checkedAll);
                // console.log('全选选择的',selection);
            },
            toggleCheckedAll(tableData,flag){
                tableData.forEach(row=>{
                    this.$refs.dictTableRef.toggleRowSelection(row,flag);
                    if(Array.isArray(row.children) && row.children.length!==0){
                        this.toggleCheckedAll(row.children,flag);
                    }
                })
            },
            init(){
                this.loadDictData();
            }
        }
    }
</script>

<style scoped>
    .explain{
        font-size: 14px;
        max-height: 100px;
        min-height: 40px;
        color: #a1a1a1;
        padding: 10px 20px;
    }
    .el-input{
        width: 180px;
    }
    .el-select-dropdown__item{
        width: 100%;
        color: darkgray;
    }
    .el-select{
        width: 120px;
    }
    .tab-list{

    }
    .import{
        color: #ffba00;
        background: #fff8e6;
        border-color: #ffe399;
    }
    .import:hover{
        opacity:0.6;
    }
    .export{
        color: #e019195e;
        background: #f3f3bfc2;
        border-color: #ffe399;
    }
    .export:hover{
        opacity: 0.6;
    }
    .tab-list{
        min-height: 99%;
    }
</style>
